#!/bin/bash

set -e

### settings
BinHome="/opt/server.lan"
MntHome="/mnt/server.lan"
TmpHome="/tmp/server.lan"
#########################################
#########################################
## do check
flag=false

ARCH=""
if uname -m | grep -F "x86_64";then
  ARCH="amd64"
elif uname -m | grep -F "x86";then
  ARCH="x86"
elif uname -m | grep -F "armv7l";then
  ARCH="armhf"
elif uname -m | grep -F "arm64";then
  ARCH="arm64"
elif uname -m | grep -F "aarch64";then
  ARCH="arm64"
else
  echo "[E] unknown ARCH , exit"
  exit 1
fi
echo "[INFO] ARCH=$ARCH"

###
systemID="`lsb_release  -is | tr A-Z a-z`"
systemCodeName="`lsb_release  -cs | tr A-Z a-z`"
systemARCH="`echo $ARCH | tr A-Z a-z`"
#amd64/
#arm64/
#armhf/
dockerDownloadUrl="https://download.docker.com/linux/${systemID}/dists/${systemCodeName}/pool/stable/${systemARCH}"

checkRequirementSoftware(){
  if ! which docker ;then
    echo "[WARN] not installed : docker 
    "
    
    {
      curl "$dockerDownloadUrl/" | grep -oE "<a href=\".+\">.*</a>" | grep -oE "href=[^>]+"
    } || true

    echo "        https://download.docker.com/linux/<debian|ubuntu>/dists/<codename>/pool/stable/<arch>/"
    echo "        $dockerDownloadUrl/"
    echo ""

    local containerd="containerd.io_1.4.13-1_$systemARCH.deb"
    local dockercecli="docker-ce-cli_20.10.15~3-0~${systemID}-${systemCodeName}_$systemARCH.deb"
    local dockerce="docker-ce_20.10.15~3-0~${systemID}-${systemCodeName}_$systemARCH.deb"

    echo "containerd=$containerd"
    echo "dockercecli=$dockercecli"
    echo "dockerce=$dockerce"

    local docker_install_sh="/tmp/install_docker.sh"
    {
        echo "#!/bin/bash"
        echo ""
        echo 'if [ -z "$1" ];then
  echo "[E] need arg1"        
  echo "usage: $0 path"
  exit 1
fi
'

cat <<EOF
(
  cd "\$1"

  wget -O "$containerd"   "$dockerDownloadUrl/$containerd"
  wget -O "$dockercecli"  "$dockerDownloadUrl/$dockercecli"
  wget -O "$dockerce"     "$dockerDownloadUrl/$dockerce"
  sudo dpkg -i "$containerd"
  sudo dpkg -i "$dockercecli"
  sudo dpkg -i "$dockerce"
)

EOF
    } | tee "$docker_install_sh"
    echo "[+] install docker run the script:: ' bash $docker_install_sh \$HOME '"
    flag=true
  fi

  if ! which borgbackup ;then
    echo "[ERR] not installed : borgbackup "
    echo "        apt install -y borgbackup "
    flag=true
  fi

  if ! which rsync ;then
    echo "[ERR] not installed : rsync "
    echo "        apt install -y rsync "
    flag=true
  fi
}

checkBinHome(){
  if [ -e "${BinHome}" ] && [ ! -d "${BinHome}" ];then
    echo "[ERR] not a dir !! : ${BinHome} "
    flag=true
  fi
}

checkMountpoint(){
  if [ "x$DIR_NOT_CHECK_MOUNTPOINT" == "xtrue" ];then
    if ! [ -d "$1" ];then
      echo "[ERR](DIR_NOT_CHECK_MOUNTPOINT==true) not dir error: $1"
      flag=true
    fi
    return
  fi

  if ! mountpoint -q "$1" ;then
    echo "[ERR] not mountpoint : $1"
    flag=true
  fi
}

checkRequirementSoftware
checkBinHome
checkMountpoint "${MntHome}/data"
checkMountpoint "${MntHome}/backup"
#checkMountpoint "${MntHome}/download"

if $flag;then
  echo "[err] Exit, check the error above. "
  exit 1
fi


##############
## check done
#########################################
##
#set docker config
echo " [i] config for docker"
docker_var="/var/lib/docker"
docker_new_var="$BinHome/disks/data/dockerVar"
if [ ! -e "$docker_new_var" ];then 
  mkdir "$docker_new_var"
fi
echo "      docker_new_var = $docker_new_var"

service docker stop
if [ -h "$docker_var" ];then
    rm "$docker_var"
elif [ -d "$docker_var" ];then
    mv "$docker_var" "${docker_var}.back"
fi

ln -s "${docker_new_var}" "$docker_var"

service docker start
echo " [ii] done = config for docker"
#####################################


copyIfExist(){
  if [ -e "$1" ];then
    echo "        copy $1 --> $2"
    cp "$1" "$2"
  fi
}


entry_script="${BinHome}/rc.local_boot.sh"
copybinfile(){  
  if [ -e "${entry_script}" ] ;then
    rm "${entry_script}"
  fi

  image="inthbl/http_server"
  docker run --pull always --rm -v "${BinHome}":/data $image

  if [ ! -e "${entry_script}" ];then
    echo "[Err] build err"
    exit 1
  fi

  copyIfExist "./http_server/rc.local_boot.sh" "${entry_script}"
  copyIfExist "./http_server/page.html" "$BinHome/www/homepage/"

  # update

  cat >"${BinHome}/http_server.update_binary.sh" <<EOF
#!/bin/bash

pid=\$(cat "$TmpHome/pid")

echo "[Warn] kill http_server pid=\$pid"
if [ -n "\$pid" ];then
  kill \$pid
  echo  > "$TmpHome/pid"
else
  echo " no pid"
fi

ps aux | grep http | grep -v grep
echo ""

echo "[INFO] update ::$image"
docker run --pull always --rm -v "${BinHome}":/data $image

echo " --> NEED reboot. "
EOF

}

copybinfile


##

########################################
echo "[INFO]  '...entry...' :: /etc/rc.local"

tmpString="#server.lan ## rc.local ### DONE "


makestartfile(){
  if ! [ -e  /etc/rc.local ];then
    echo "[E] not exist error::  /etc/rc.local"
    return
  fi


  if grep -E "^$tmpString" /etc/rc.local &> /dev/null;then
    echo "[i] rc.local is already OK, no need to change"
    return
  fi

  tmpRC="/tmp/rc.local"
  sed  "s/^ *exit /#exit /g" /etc/rc.local > "$tmpRC"

  # entry
  {
    cat <<EOF
$tmpString
start_http_server(){
  entry="${entry_script}"
  if [ -e "\${entry}" ];then
    bash  "\${entry}" &
  fi

  entry="$(dirname "${entry_script}")/custom_entry.sh"
  if [ -e "\${entry}" ];then
    bash  "\${entry}" &
  fi

}

start_http_server

exit 0
EOF
  } | tee -a  "$tmpRC" #
  ## or /etc/init.d/...... service

  cp "$tmpRC" /etc/rc.local

  echo "[i] done :: entry in /etc/rc.local 
  
  "
}


makestartfile


